﻿using System.Diagnostics;
using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using TianlalaHSB.Models;
using TianlalaHSB.Utils;

namespace TianlalaHSB.Views;

/// <summary>
///     AccountView.xaml 的交互逻辑
/// </summary>
public partial class AccountView : Page
{
    public AccountView()
    {
        InitializeComponent();
    }

    private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = !Number.IsInteger(e.Text);
    }

    private async void SubmitButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var subAcctNoVal = subAcctNo.Text.Trim();
            var memberNoVal = memberNo.Text.Trim();

            if (Validation.GetHasError(subAcctNo)) throw new Exception("资金账号格式被正确");

            if (string.IsNullOrEmpty(subAcctNoVal) && string.IsNullOrEmpty(memberNoVal))
                throw new Exception("资金账号与会员代码不能同时为空");

            // 准备POST请求的数据 
            var postData = new
            {
                headReqSerialNo = HttpUtil.GetHeadReqSerialNo(),
                subAcctNo = subAcctNoVal
            };

            var responseBody = await HttpUtil.Request("03050103A1018", postData);
            var list = JsonSerializer.Deserialize<ResponseList<Account>>(responseBody);
            if (list == null) throw new Exception("无数据");

            // 在这里处理获取到的数据，例如更新UI
            RecordListView.ItemsSource = list.dtos;
        }
        catch (Exception ex)
        {
            // 处理异常，例如网络问题或无效的请求等
            MessageBox.Show(ex.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void ViewButton_Click(object sender, RoutedEventArgs e)
    {
        if (sender is not Button { Tag: Account item }) return;

        // 创建并显示详情页
        var detailWindow = new AccountDetailView(item)
        {
            WindowStartupLocation = WindowStartupLocation.CenterScreen,
            Width = 600,
            Height = 500
        };
        detailWindow.ShowWindow();
    }

    private void Bind_Click(object sender, RoutedEventArgs e)
    {
        var url = "https://www.baidu.com"; // 替换为你想要打开的链接
        Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true });
    }

    private void Unbind_Click(object sender, RoutedEventArgs e)
    {
        var url = "https://www.baidu.com"; // 替换为你想要打开的链接
        Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true });
    }
}